<template>
	<view class="personal-center">
		<u-form :model="userForm" ref="uForm" :border-bottom="false">
			<!-- 1. 头像上传 -->
			<u-form-item label="头像" label-width="150">
				<view class="upload-box">
					<view class="img-preview hover-press" @click="chooseImg('userAvatar')">
						<image mode="aspectFill" :src="avatarUrl || defaultAvatar"></image>
						<view class="del-btn" v-if="userForm.userAvatar" @click.stop="delImg('userAvatar')">✕</view>
					</view>
					<view class="tip">点击上传/修改头像</view>
				</view>
			</u-form-item>

			<!-- 2. 基础信息 -->
			<u-form-item label="姓名" prop="userName" required label-width="150">
				<u-input v-model="userForm.userName" placeholder="请输入姓名" />
			</u-form-item>

			<u-form-item label="年龄" prop="age" required label-width="150">
				<u-input v-model="userForm.userAge" placeholder="请输入年龄" />
			</u-form-item>

			<u-form-item label="性别" prop="userGender" required label-width="150">
				<u-radio-group v-model="userForm.userGender">
					<u-radio :name="'男'" active-color="#2979ff">男</u-radio>
					<u-radio :name="'女'" active-color="#2979ff">女</u-radio>
				</u-radio-group>
			</u-form-item>

			<u-form-item label="身高(cm)" prop="userHeight" label-width="150">
				<u-input v-model="userForm.userHeight" placeholder="请输入身高" type="number" />
			</u-form-item>

			<u-form-item label="体重(kg)" prop="userWeight" label-width="150">
				<u-input v-model="userForm.userWeight" placeholder="请输入体重" type="number" />
			</u-form-item>

			<u-form-item label="手机号" prop="userPhoneNumber" required label-width="150">
				<u-input v-model="userForm.userPhoneNumber" placeholder="请输入手机号" type="number" />
			</u-form-item>

			<u-form-item label="验证码" prop="code" required label-width="150">
				<view class="code-box">
					<u-input v-model="userForm.code" placeholder="请输入验证码" type="number" />
					<u-button type="primary" size="mini" :disabled="count > 0" @click="sendCode">
						{{ count > 0 ? `${count}s后重发` : '获取验证码' }}
					</u-button>
				</view>
			</u-form-item>

			<u-form-item label="身份证号" prop="userIdCard" required label-width="150">
				<u-input v-model="userForm.userIdCard" placeholder="请输入18位身份证号" />
			</u-form-item>

			<!-- 3. 身份证正反面上传 -->
			<u-form-item label="身份证上传" label-width="150">
				<view class="idcard-box">
					<!-- 身份证正面 -->
					<view class="upload-box">
						<view class="img-title">正面（人像面）</view>
						<view class="img-preview hover-press" @click="chooseImg('frontIdCard')">
							<image mode="aspectFill" :src="idCardFrontUrl || defaultIdCard"></image>
							<view class="del-btn" v-if="userForm.frontIdCard" @click.stop="delImg('frontIdCard')">✕
							</view>
						</view>
					</view>
					<!-- 身份证反面 -->
					<view class="upload-box">
						<view class="img-title">反面（国徽面）</view>
						<view class="img-preview hover-press" @click="chooseImg('reverseIdCard')">
							<image mode="aspectFill" :src="idCardBackUrl || defaultIdCard"></image>
							<view class="del-btn" v-if="userForm.reverseIdCard" @click.stop="delImg('reverseIdCard')">✕
							</view>
						</view>
					</view>
				</view>
			</u-form-item>

			<!-- 4. 提交按钮 -->
			<view class="submit-btn">
				<u-button type="primary" shape="circle" @click="saveInfo" :loading="isLoading">
					保存信息
				</u-button>
			</view>
		</u-form>
	</view>
</template>

<script>
	import {
		queryUser,
		updateUser,
		sendCode
	} from '@/api/mine.js'

	// 设置请求超时时间（毫秒）
	const REQUEST_TIMEOUT = 10000;

	export default {
		data() {
			return {
				// 核心表单数据
				userForm: {
					userName: '',
					userAge: '',
					userGender: '',
					userHeight: '',
					userWeight: '',
					userPhoneNumber: '',
					code: '',
					userIdCard: '',
					userAvatar: '',
					frontIdCard: '',
					reverseIdCard: ''
				},
				// 图片本地预览URL
				avatarUrl: '',
				idCardFrontUrl: '',
				idCardBackUrl: '',
				// 基础状态变量
				defaultAvatar: '/static/default-avatar.png',
				defaultIdCard: '/static/default-idcard.png',
				count: 0,
				timer: null,
				isLoading: false,
				// 表单校验规则
				rules: {
					userName: [{
						required: true,
						message: '请填写姓名',
						trigger: 'blur'
					}],
					userPhoneNumber: [{
							required: true,
							message: '请填写手机号',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号格式不正确',
							trigger: 'blur'
						}
					],
					code: [{
						required: true,
						message: '请填写验证码',
						trigger: 'blur'
					}],
					userIdCard: [{
							required: true,
							message: '请填写身份证号',
							trigger: 'blur'
						},
						{
							pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
							message: '身份证号格式不正确',
							trigger: 'blur'
						}
					]
				}
			};
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.loadUserInfo();
		},
		methods: {
			// 加载用户信息
			loadUserInfo() {
				uni.showLoading({
					title: '加载中...'
				});

				let temp = {
					id: this.$store.state.userId
				};

				// 设置超时处理
				const timeoutPromise = new Promise((_, reject) => {
					setTimeout(() => reject(new Error('请求超时')), REQUEST_TIMEOUT);
				});

				Promise.race([queryUser(temp), timeoutPromise])
					.then(res => {
						uni.hideLoading();
						if (res.code === 1) {
							this.userForm = res.data;
							// 直接使用后端返回的性别值（男/女）
							this.userForm.userGender = res.data.userGender;

							// 处理图片路径
							if (res.data.userAvatar) {
								this.avatarUrl = this.processImageUrl(res.data.userAvatar);
								this.userForm.userAvatar = res.data.userAvatar;
							}
							if (res.data.frontIdCard) {
								this.idCardFrontUrl = this.processImageUrl(res.data.frontIdCard);
								this.userForm.frontIdCard = res.data.frontIdCard;
							}
							if (res.data.reverseIdCard) {
								this.idCardBackUrl = this.processImageUrl(res.data.reverseIdCard);
								this.userForm.reverseIdCard = res.data.reverseIdCard;
							}
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error('加载用户信息失败:', err);
						uni.showToast({
							title: err.message === '请求超时' ? '网络连接超时，请重试' : '加载失败',
							icon: 'none'
						});
					});
			},

			// 处理图片URL
			processImageUrl(url) {
				if (!url) return '';
				// 如果已经是完整URL，直接返回
				if (url.startsWith('http')) return url;
				// 如果是相对路径，添加基础URL
				return `http://127.0.0.1:9300${url.startsWith('/') ? '' : '/'}${url}`;
			},

			// 选择图片
			chooseImg(field) {
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success: async (chooseRes) => {
						const tempFilePath = chooseRes.tempFilePaths[0];
						const tempFile = chooseRes.tempFiles[0];

						// 文件大小检查
						if (tempFile.size > 5 * 1024 * 1024) {
							uni.showToast({
								title: '图片大小不能超过5MB',
								icon: 'none'
							});
							return;
						}

						// 设置预览图
						if (field === 'userAvatar') {
							this.avatarUrl = tempFilePath;
						} else if (field === 'frontIdCard') {
							this.idCardFrontUrl = tempFilePath;
						} else if (field === 'reverseIdCard') {
							this.idCardBackUrl = tempFilePath;
						}

						// 上传图片
						try {
							const imageUrl = await this.uploadImg(tempFilePath, field);
							console.log('上传成功返回的数据:', imageUrl);

							// 更新表单数据和预览图
							this.userForm[field] = imageUrl;

							if (field === 'userAvatar') {
								this.avatarUrl = this.processImageUrl(imageUrl);
							} else if (field === 'frontIdCard') {
								this.idCardFrontUrl = this.processImageUrl(imageUrl);
							} else if (field === 'reverseIdCard') {
								this.idCardBackUrl = this.processImageUrl(imageUrl);
							}

							uni.showToast({
								title: '上传成功'
							});
						} catch (error) {
							console.error('上传失败:', error);
							uni.showToast({
								title: error.message || '上传失败',
								icon: 'none'
							});

							// 上传失败清除预览
							if (field === 'userAvatar') {
								this.avatarUrl = '';
							} else if (field === 'frontIdCard') {
								this.idCardFrontUrl = '';
							} else if (field === 'reverseIdCard') {
								this.idCardBackUrl = '';
							}
						}
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 上传图片
			uploadImg(filePath, field) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 确定上传类型
					const typeMap = {
						'userAvatar': 'avatar',
						'frontIdCard': 'idcard_front',
						'reverseIdCard': 'idcard_back'
					};
					const uploadType = typeMap[field] || 'other';

					// 设置超时处理
					const timeoutPromise = new Promise((_, reject) => {
						setTimeout(() => reject(new Error('上传超时')), REQUEST_TIMEOUT);
					});

					// 使用 uni.uploadFile 上传
					const uploadTask = uni.uploadFile({
						url: '/health-api/file/upload', // 替换为您的实际上传接口
						filePath: filePath,
						name: 'file',
						formData: {
							type: uploadType
						},
						success: (uploadRes) => {
							uni.hideLoading();

							try {
								const resData = JSON.parse(uploadRes.data);
								console.log('上传接口返回数据:', resData);

								if (resData.code === 200) {
									// 根据返回的数据结构，提取fileUrl字段
									if (resData.data && resData.data.fileUrl) {
										resolve(resData.data.fileUrl);
									} else {
										reject(new Error('服务器返回的数据格式不正确，缺少fileUrl字段'));
									}
								} else {
									reject(new Error(resData.msg || '上传失败'));
								}
							} catch (e) {
								console.error('解析服务器返回数据失败:', e);
								reject(new Error('服务器返回格式错误'));
							}
						},
						fail: (err) => {
							uni.hideLoading();
							console.error('上传请求失败:', err);
							reject(err);
						}
					});

					// 处理超时
					timeoutPromise.catch(() => {
						uploadTask.abort();
						reject(new Error('上传超时'));
					});
				});
			},

			// 删除图片
			delImg(field) {
				this.userForm[field] = '';
				if (field === 'userAvatar') {
					this.avatarUrl = '';
				} else if (field === 'frontIdCard') {
					this.idCardFrontUrl = '';
				} else if (field === 'reverseIdCard') {
					this.idCardBackUrl = '';
				}
				uni.showToast({
					title: '图片已删除'
				});
			},

			// 发送验证码
			sendCode() {
				const phone = this.userForm.userPhoneNumber;
				if (!phone) {
					uni.showToast({
						title: '请先填写手机号',
						icon: 'none'
					});
					return;
				}
				if (!/^1[3-9]\d{9}$/.test(phone)) {
					uni.showToast({
						title: '请填写正确的手机号',
						icon: 'none'
					});
					return;
				}

				let temp = {
					phone: phone
				}

				// 设置超时处理
				const timeoutPromise = new Promise((_, reject) => {
					setTimeout(() => reject(new Error('请求超时')), REQUEST_TIMEOUT);
				});

				Promise.race([sendCode(temp), timeoutPromise])
					.then(res => {
						console.log(res)
						if (res.code === 1) {
							uni.showToast({
								title: '验证码已发送'
							});
							this.count = 60;
							this.timer = setInterval(() => {
								this.count--;
								if (this.count <= 0) {
									clearInterval(this.timer);
									this.timer = null;
								}
							}, 1000);
						} else {
							uni.showToast({
								title: res.msg || '验证码发送失败，请重新发送',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('发送验证码失败:', err);
						uni.showToast({
							title: err.message === '请求超时' ? '网络连接超时，请重试' : '验证码发送失败',
							icon: 'none'
						});
					});
			},

			// 保存信息
			async saveInfo() {
				console.log("保存信息", this.userForm)
				// 表单校验
				try {
					await this.$refs.uForm.validate();
				} catch (e) {
					return;
				}

				// 图片上传校验
				if (!this.userForm.userAvatar) {
					uni.showToast({
						title: '请上传头像',
						icon: 'none'
					});
					return;
				}
				if (!this.userForm.frontIdCard || !this.userForm.reverseIdCard) {
					uni.showToast({
						title: '请上传身份证正反面',
						icon: 'none'
					});
					return;
				}

				// 提交数据
				this.isLoading = true;

				try {
					let temp = {
						id: this.userForm.userId,
						code: this.userForm.code,
						phone: this.userForm.userPhoneNumber,
						userName: this.userForm.userName,
						userHeight: this.userForm.userHeight,
						userWeight: this.userForm.userWeight,
						userIdCard: this.userForm.userIdCard,
						frontIdCard: this.userForm.frontIdCard,
						reverseIdCard: this.userForm.reverseIdCard,
						userAge: this.userForm.userAge,
						gender: this.userForm.userGender, // 直接使用"男"/"女"
						userAvatar: this.userForm.userAvatar
					}

					// 设置超时处理
					const timeoutPromise = new Promise((_, reject) => {
						setTimeout(() => reject(new Error('请求超时')), REQUEST_TIMEOUT);
					});

					const res = await Promise.race([updateUser(temp), timeoutPromise]);

					//console.log(res)
					if (res.code === 1) {
						uni.showToast({
							title: '信息保存成功'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '信息保存失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('保存失败:', err);
					uni.showToast({
						title: err.message === '请求超时' ? '网络连接超时，请重试' : '保存失败，请重试',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			}
		},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		}
	}
</script>

<style>
	.personal-center {
		padding: 20rpx;
		background: #ffffff;
		min-height: 100vh;
	}

	.upload-box {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.upload-box .img-title {
		margin-bottom: 12rpx;
		font-size: 24rpx;
		color: #666666;
		font-weight: 500;
	}

	.upload-box .img-preview {
		width: 160rpx;
		height: 160rpx;
		border: 1px solid #eeeeee;
		border-radius: 50%;
		overflow: hidden;
		position: relative;
		background-color: #f9f9f9;
	}

	.upload-box .img-preview image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-box .img-preview .del-btn {
		position: absolute;
		right: 0;
		top: 0;
		width: 36rpx;
		height: 36rpx;
		background: rgba(0, 0, 0, 0.5);
		color: #ffffff;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		z-index: 10;
	}

	.upload-box .tip {
		margin-top: 10rpx;
		font-size: 20rpx;
		color: #999999;
	}

	.idcard-box {
		display: flex;
		justify-content: space-between;
		width: 100%;
		margin-top: 10rpx;
	}

	.idcard-box .upload-box {
		width: 48%;
	}

	.idcard-box .img-preview {
		border-radius: 8rpx;
		height: 220rpx;
		border-radius: 12rpx;
	}

	.code-box {
		display: flex;
		align-items: center;
		width: 100%;
	}

	.code-box .u-input {
		flex: 1;
	}

	.code-box .u-button {
		margin-left: 20rpx;
		white-space: nowrap;
		padding: 0 24rpx;
	}

	.submit-btn {
		margin-top: 60rpx;
		padding: 0 20rpx;
	}

	.hover-press:active {
		opacity: 0.8;
		transform: scale(0.98);
		transition: all 0.2s ease;
	}
</style>